package com.hancai.aspect;

import com.hancai.commons.DataScope;
import com.hancai.constant.Constants;
import com.hancai.model.TUser;
import com.hancai.query.BaseQuery;
import com.hancai.util.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author 涵菜
 * @version 1.0
 */
@Aspect
@Component
public class DataScopeAspect {

    @Pointcut(value = "@annotation(com.hancai.commons.DataScope)")
    public void pointCut(){

    }

    @Around(value="pointCut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature=(MethodSignature)joinPoint.getSignature();
        //拿到方法上的注解
        Method method = methodSignature.getMethod();
        DataScope dataScope = method.getDeclaredAnnotation(DataScope.class);
        //拿到注解的属性
        String tableAlias = dataScope.tableAlias();
        String tableField = dataScope.tableField();
        //在spring web容器中，拿到当前的request对象
        HttpServletRequest request=
                ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Constants.TOKEN_NAME);
        //从token中解析出该用户是管理员还是普通用户(生成token的时候把角色放入)
        TUser tUser = JWTUtils.parseUserFromJWT(token);
        List<String> roleList = tUser.getRoleList();
        if (!roleList.contains("admin")) {
            //只查看当前用户自己的数据,如果角色有管理员的话，就可以查询所有数据
            //拿到selectUserByPage方法的第一个参数
            Object param = joinPoint.getArgs()[0];
            if(param instanceof BaseQuery){
                BaseQuery query=(BaseQuery)param;
                query.setFilterSQL(" and " + tableAlias+ "." + tableField + " = " +tUser.getId());
            }
        }
        return joinPoint.proceed();//执行目标方法-pointCut
    }
}
